#!/bin/bash

nginx=/web/nginx
php=/web/php
fpm=$php/sbin/php-fpm

myexit() {
    echo ${1-exit}
    exit ${2-0}
}

isRun() {
    nginx_bin=${1-/web/nginx/sbin/nginx}
    run=$(ps -aux | grep $nginx_bin 2> /dev/null | grep -v 'grep')
    test -z "$run" && echo "close"
}

stop() {
    test "$(isRun)" = "close" && myexit "没有启动nginx!"
    sudo $nginx/sbin/nginx -s stop
    sudo pkill fpm
}

reload() {
    test "$(isRun)" = "close" && myexit "没有启动nginx!"
    sudo $nginx/sbin/nginx -s reload
}

start() {
    test "$(isRun apache)" != "close" && /web/bin/lamp stop
    test "$(isRun)" != "close" && stop
    sudo $fpm -D -y $php/etc/php-fpm.conf
    sudo $nginx/sbin/nginx
}

restart() {
    start
}

vhost() {

    test $UID -ne 0 && myexit "请使用sudo运行!" 1

    grep " php.com" /etc/hosts &> /dev/null \
            || echo "$srvip php.com" >> /etc/hosts

    path=${1-/kyo}

    test "$path" = "." && path=$(pwd)

    echo "root $path;" > $nginx/conf/kyo_root.conf

    restart
}

cmd=${1-restart}

test -d $cmd && vhost $cmd || $cmd
